package com.example.fuluchou.service.impl;

import com.example.fuluchou.controller.param.CreatePrizeParam;
import com.example.fuluchou.controller.param.PageParam;
import com.example.fuluchou.dao.dataobject.PrizeDO;
import com.example.fuluchou.dao.mapper.PrizeMapper;
import com.example.fuluchou.service.PictureService;
import com.example.fuluchou.service.PrizeService;
import com.example.fuluchou.service.dto.PageListDTO;
import com.example.fuluchou.service.dto.PrizeDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;


@Service
public class PrizeServiceImpl implements PrizeService {
    private static final Logger logger = LoggerFactory.getLogger(PrizeServiceImpl.class);

    @Autowired
    private PictureService pictureService;

    @Autowired
    private PrizeMapper prizeMapper;

    @Override
    public Long createPrize(CreatePrizeParam param, MultipartFile picFile){
        //整理奖品信息
        PrizeDO prizeDO = new PrizeDO();
        prizeDO.setDescription(param.getDescription());
        prizeDO.setName(param.getPrizeName());
        prizeDO.setPrice(param.getPrice());
        //保存图片
        logger.info("开始保存图片{}",picFile.getOriginalFilename());
        String file = pictureService.savePicture(picFile);
        prizeDO.setImageurl(file);
        prizeMapper.insert(prizeDO);
        return  prizeDO.getId();
    }

    @Override
    public PageListDTO<PrizeDTO> findPrizeList(PageParam param){
        Long total = prizeMapper.count();
        List<PrizeDO> prizeDOList = prizeMapper.queryPrizesByPage(param.offset(),param.getPageSize());
        List<PrizeDTO> prizeDTOList = new ArrayList<>();
        for(PrizeDO prizeDO:prizeDOList){
            PrizeDTO prizeDTO = new PrizeDTO();

            prizeDTO.setPrizeId(prizeDO.getId());
            prizeDTO.setDescription(prizeDO.getDescription());
            prizeDTO.setName(prizeDO.getName());
            prizeDTO.setPrice(prizeDO.getPrice());
            prizeDTO.setImage_url(prizeDO.getImageurl());
            prizeDTOList.add(prizeDTO);
        }
        return new PageListDTO(total,prizeDTOList);
    }
}
